<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4">
        <el-input
          v-model="filterText"
          clearable
          style="width:90%; margin-bottom: 20px;"
          prefix-icon="el-icon-search"
          placeholder="输入部门名称搜索"
        />
        <el-tree
          ref="tree"
          class="filter-tree"
          :data="departmentsData"
          :props="defaultProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
        />
      </el-col>
      <el-col :span="20">
        <el-form ref="form" :model="form" inline>
          <el-form-item prop="search">
            <el-input
              v-model="form.search"
              clearable
              style="width:300px"
              prefix-icon="el-icon-search"
              placeholder="输入用户名、姓名、手机号、邮箱搜索"
            />
          </el-form-item>
          <el-form-item prop="is_active">
            <el-select v-model="form.is_active" style="width:100px" clearable placeholder="状态">
              <el-option label="激活" value="true"/>
              <el-option label="锁定" value="false"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="success" icon="el-icon-search" size="medium" @click="search(form)">搜索</el-button>
            <el-button type="warning" icon="el-icon-refresh-left" size="medium" @click="resetForm()">重置</el-button>
          </el-form-item>
        </el-form>
        <el-button
          v-permission="['admin','system-users-add']"
          type="primary"
          style="margin-bottom:20px"
          icon="el-icon-plus"
          size="medium"
          @click="createUser()"
        >新增
        </el-button>
        <el-button
          v-permission="['admin','system-users-mdel']"
          type="danger"
          icon="el-icon-delete"
          :disabled="multipleSelection.length ? false : true"
          size="medium"
          @click="deleteUsers(form)"
        >删除
        </el-button>
        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChange"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column
            prop="userName"
            label="用户名"
            width="120"
            sortable="custom"
          />
          <el-table-column
            prop="fullName"
            label="姓名"
            width="120"
            sortable="custom"
          />
          <el-table-column
            prop="mobile"
            label="电话"
            width="120"
          />
          <el-table-column
            prop="email"
            label="邮箱"
            width="150"
          />
          <el-table-column
            prop="departmentName"
            label="部门"
            width="100"
          />
          <el-table-column
            prop="rolesName"
            label="角色"
            :formatter="formatList"
          />
          <el-table-column
            prop="lastLoginDateTime"
            label="最后登录时间"
            width="150"
          />
          <el-table-column
            label="状态"
            align="center"
            width="100"
          >
            <template slot-scope="{row}">
              <el-switch
                v-model="row.isActive"
                :disabled="!checkPermission(['admin','system-users-lock'])||row.id === userID"
                :active-value="true"
                :inactive-value="false"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="changeIsActive($event, row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            align="center"
            label="操作"
            width="230"
          >
            <template slot-scope="{row}">
              <el-button
                v-permission="['admin','system-users-update']"
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="updateUser(row)"
              />
              <el-button
                v-permission="['admin','system-users-del']"
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteUser(row)"
              />
              <el-tooltip content="用户权限" placement="top">
                <el-button
                  v-permission="['admin','system-users-permissions']"
                  type="warning"
                  icon="el-icon-user-solid"
                  size="mini"
                  @click="userPermissions(row)"
                />
              </el-tooltip>
              <el-tooltip content="重置密码" placement="top">
                <el-button
                  v-permission="['admin','system-users-reset-pwd']"
                  type="warning"
                  size="mini"
                  @click="resetPass(row)"
                >
                  <svg-icon icon-class="reset_password"/>
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <el-pagination
          :current-page="1"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="10"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>
    <cuForm
      :dialog-visible="cuDialogVisible"
      :departments-data="departmentsData"
      :cur-id="curId"
      @close="close"
      @search="search"
    />
    <resetPwdForm
      :resetPassDialogVisible="resetPassDialogVisible"
      :resetCurId="curId"
      @resetClose="resetClose"
    />
    <permissionsDialog
      :permissions-dialog-visible="permissionsDialogVisible"
      :userID="curId"
      @permissionsClose="permissionsClose"
    />
  </div>
</template>

<script>
import checkPermission from '@/utils/permission'
import cuForm from './components/cuForm'
import resetPwdForm from './components/resetPwdForm'
import permissionsDialog from './components/permissionsDialog'
import { getUsers, updateUserActive, deleteUser, deleteUsers } from '@/api/system/users'
import { getDepartmentsTreeData } from '@/api/system/departments'
import { mapGetters } from 'vuex'
import { cleanNull } from '@/utils/filters'

export default {
  name: 'Users',
  components: { cuForm, resetPwdForm, permissionsDialog },
  data() {
    return {
      form: {
        page: 1,
        size: 10,
        sortField: 'userName',
        ascending: true,
        search: '',
        isActive: '',
        departmentID: ''
      },
      tableData: [],
      total: 0,
      multipleSelection: [], // 已选择的用户id数组
      filterText: '',
      departmentsData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 以下为cuForm子组件数据
      cuDialogVisible: false,
      curId: null,
      // 以下为resetPwdForm子组件数据
      resetPassDialogVisible: false,
      // permissionsDialog子组件
      permissionsDialogVisible: false
    }
  },
  computed: {
    ...mapGetters([
      'userID'
    ])
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.search()
    this.getDepartments()
  },
  methods: {
    checkPermission,
    formatList(row, column, cellValue) {
      return cellValue.join(', ')
    },
    // 获取部门Tree结构
    getDepartments() {
      getDepartmentsTreeData().then(res => {
        this.departmentsData = res.data
        this.departmentsData = cleanNull(this.departmentsData)
      })
    },
    // 部门Tree过滤方法
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 过滤部门下的用户列表
    handleNodeClick(data) {
      this.form.departmentID = data.id
      this.search()
    },
    // 获取用户列表/搜索功能
    search() {
      getUsers(this.form).then(res => {
        this.tableData = res.data.data
        this.total = res.data.count
      })
    },
    // 重置
    resetForm() {
      this.$refs.form.resetFields()
      // form中未使用department_id字段需手动清除
      this.form.departmentID = ''
      // 使用 Object.assign() 将 form 重置为初始值
      this.form = Object.assign({}, this.$options.data().form)
      this.search()
    },
    // 修改用户状态
    changeIsActive(event, row) {
      const message = !event ? '锁定' : '激活'
      this.$confirm('此操作将' + message + '用户 "' + row.userName + '" , 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateUserActive(row.id, row.isActive).then(res => {
          this.$message({
            message: message + row.userName + '成功',
            type: 'success'
          })
        }).catch(() => {
          row.isActive = !row.isActive
        })
      }).catch(() => {
        row.isActive = !row.isActive
      })
    },
    // 删除用户
    deleteUser(row) {
      this.$confirm('此操作将删除用户 "' + row.userName + '" , 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(row.id).then(res => {
          this.$message({
            message: '删除用户' + row.userName + '成功',
            type: 'success'
          })
          // 刷新table
          this.search()
        })
      })
    },

    // table选择功能的change事件
    handleSelectionChange() {
      const deleteIds = []
      this.$refs.multipleTable.selection.forEach(data => deleteIds.push(data.id))
      this.multipleSelection = deleteIds
    },
    // 自定义排序
    handleSortChange({ column, prop, order }) {
      this.form.sortField = order === null ? '' : prop
      this.form.ascending = order === 'ascending'
      this.search()
    },

    // 批量删除用户
    deleteUsers() {
      this.$confirm('此操作将删除选中用户' + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUsers(this.multipleSelection).then(res => {
          this.$message({
            message: '删除用户成功',
            type: 'success'
          })
          // 刷新table
          this.search()
        })
      })
    },
    // 分页
    handleSizeChange(val) {
      this.form.size = val
      this.search()
    },
    handleCurrentChange(val) {
      this.form.page = val
      this.search()
    },
    // cuForm子组件
    createUser() {
      this.cuDialogVisible = true
    },
    updateUser(row) {
      this.curId = row.id
      this.cuDialogVisible = true
    },
    close() {
      this.cuDialogVisible = false
      this.curId = null
    },
    // 重置密码子组件
    resetPass(row) {
      this.resetPassDialogVisible = true
      this.curId = row.id
    },
    resetClose() {
      this.resetPassDialogVisible = false
      this.curId = null
    },
    // 用户权限组件
    userPermissions(row) {
      this.permissionsDialogVisible = true
      this.curId = row.id
    },
    permissionsClose() {
      this.permissionsDialogVisible = false
      this.curId = null
    }
  }

}
</script>
